const express = require("express");
const router = express.Router();
// hash密码
const bcrypt = require("bcrypt");
// 工具
const _ = require("lodash");

const path = require("path");
const dirname = path.resolve();
const { User, validateLogin } = require(path.join(dirname, "src/model/user"));

// 用户登录
router.post("/", async (req, res) => {
  const { error } = validateLogin(req.body);
  if (error) return res.status(400).send({ message: error.message });

  const user = await User.findOne({ email: req.body.email });
  if (!user) return res.status(400).send({ message: "邮箱地址或者密码错误" });

  const validPassword = await bcrypt.compare(req.body.password, user.password);
  if (!validPassword)
    return res.status(400).send({ message: "邮箱地址或者密码错误" });

  // 将用户信息存储在session中
  req.session.userInfo = user;
  res.send({ data: _.pick(user, ["username", "email", "avatar", "_id"]) });
});

// 导出路由
module.exports = router;
